package http_servicer

import (
	//	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	//	"net"
	"ifms/db_servicer"
	//	"ifms/tcp_servicer"
)

// This script implement the function related with device information,
//  including  information in table device_data, device_align, device_sensor_threashold
//

//	router.HandleFunc("/realtimepondinfo", realtimepondinfoHandler).Methods("POST")

//

func pondHistDataHourlyHandler(response http.ResponseWriter, request *http.Request) {
	// logger = log.New(os.Stdout, ">>>>>>>> Pond Hist Data Summary durying pecfic time window:", log.LstdFlags|log.Lshortfile)

	v_session_id, v_user_id := getAccountName(request)

	v_pond_id := request.FormValue("pond_id")
	from_date := request.FormValue("from_date")
	to_date := request.FormValue("to_date")

	logger.Println("\n>>>session_id:", v_session_id, ", user_id :", v_user_id)

	logger.Println("\n>>>pond_id :", v_pond_id, ", from_date  :", from_date, ", to_date:", to_date)

	if v_user_id == 0 {
		reloginPage(response, request)
		return
	}

	var pond_id int
	var msg string = " Not an valid date format(yyyy/mm/dd)"
	var err error

	if pond_id, err = strconv.Atoi(v_pond_id); err != nil && v_pond_id != "" {
		msg = msg + " pond_id :" + v_pond_id
	}

	if !ValidDateFormat(from_date) {
		msg = msg + ", From date: " + from_date
	}
	if !ValidDateFormat(to_date) {
		msg = msg + ", To date: " + to_date
	}

	if msg > "Not an valid date format(yyyy/mm/dd)" {
		logger.Println("\nError:", err)
		logger.Println("\nMsg:", msg)
		fmt.Fprintf(response, `{"flag":-1,"message":"%s" }`, msg)
	} else {

		//	var responseStr []byte

		dbmsg := db_servicer.PondInfo_HistDaily(v_user_id, pond_id, from_date, to_date, "hourly")

		//	logger.Println("dbmsg:", dbmsg)
		//	logger.Println("\n>>>Return to App Client:", dbmsg.Data)
		fmt.Fprint(response, dbmsg.Data)

	}
}

func pondHistDataDailyHandler(response http.ResponseWriter, request *http.Request) {
	// logger = log.New(os.Stdout, ">>>>>>>> Pond Hist Data Summary durying pecfic time window:", log.LstdFlags|log.Lshortfile)

	v_session_id, v_user_id := getAccountName(request)

	v_pond_id := request.FormValue("pond_id")
	from_date := request.FormValue("from_date")
	to_date := request.FormValue("to_date")

	logger.Println("\n>>>session_id:", v_session_id, ", user_id :", v_user_id)

	logger.Println("\n>>>pond_id :", v_pond_id, ", from_date  :", from_date, ", to_date:", to_date)

	if v_user_id == 0 {
		reloginPage(response, request)
		return
	}

	var pond_id int
	var msg string = " Not an valid date format(yyyy/mm/dd)"
	var err error

	if pond_id, err = strconv.Atoi(v_pond_id); err != nil && v_pond_id != "" {
		msg = msg + " pond_id :" + v_pond_id
	}

	if !ValidDateFormat(from_date) {
		msg = msg + ", From date: " + from_date
	}
	if !ValidDateFormat(to_date) {
		msg = msg + ", To date: " + to_date
	}

	if msg > "Not an valid date format(yyyy/mm/dd)" {
		logger.Println("\nError:", err)
		logger.Println("\nMsg:", msg)
		fmt.Fprintf(response, `{"flag":-1,"message":"%s" }`, msg)
	} else {

		//	var responseStr []byte

		dbmsg := db_servicer.PondInfo_HistDaily(v_user_id, pond_id, from_date, to_date, "daily")

		//	logger.Println("dbmsg:", dbmsg)
		//	logger.Println("\n>>>Return to App Client:", dbmsg.Data)
		fmt.Fprint(response, dbmsg.Data)

	}
}

func pondHistDataListHandler(response http.ResponseWriter, request *http.Request) {
	// logger = log.New(os.Stdout, ">>>>>>>> Pond Hist Data List in Specfic day:", log.LstdFlags|log.Lshortfile)

	v_session_id, v_user_id := getAccountName(request)

	v_pond_id := request.FormValue("pond_id")
	qry_date := request.FormValue("qry_date")

	logger.Println("\n>>>session_id:", v_session_id, ", user_id :", v_user_id)

	logger.Println("\n>>>pond_id :", v_pond_id, ", qry_date  :", qry_date)

	if v_user_id == 0 {
		reloginPage(response, request)
		return
	}

	var pond_id int
	var msg string = "Not an valid date format(yyyy/mm/dd)"
	var err error

	if pond_id, err = strconv.Atoi(v_pond_id); err != nil && v_pond_id != "" {
		msg = msg + " pond_id :" + v_pond_id
	}

	if !ValidDateFormat(qry_date) {
		msg = msg + qry_date
	}

	if msg > "Not an valid date format(yyyy/mm/dd)" {
		logger.Println("\nError:", err)
		logger.Println("\nMsg:", msg)
		fmt.Fprintf(response, `{"flag":-1,"message":"%s" }`, msg)
	} else {

		//	var responseStr []byte

		dbmsg := db_servicer.PondInfo_HistList(v_user_id, pond_id, qry_date)

		//	logger.Println("dbmsg:", dbmsg)
		//	logger.Println("\n>>>Return to App Client:", dbmsg.Data)
		fmt.Fprint(response, dbmsg.Data)

	}
}

func realtimepondinfoHandler(response http.ResponseWriter, request *http.Request) {
	// logger = log.New(os.Stdout, ">>>>>>>> Real Time Pond Info:", log.LstdFlags|log.Lshortfile)

	v_session_id, v_user_id := getAccountName(request)

	logger.Println("\n>>>session_id:", v_session_id, ", user_id :", v_user_id)

	if v_user_id == 0 {
		reloginPage(response, request)
		return
	}

	//	var responseStr []byte

	dbmsg := db_servicer.Realtime_PondInfo(v_user_id)

	//	logger.Println("dbmsg:", dbmsg)
	logger.Println("\n>>>Return to App Client:", dbmsg.Data)
	fmt.Fprint(response, dbmsg.Data)

}

func setDeviceMarginHandler(response http.ResponseWriter, request *http.Request) {
	// logger = log.New(os.Stdout, ">>>>>>>> Set Device Margin :", log.LstdFlags|log.Lshortfile)

	v_session_id, v_user_id := getAccountName(request)

	logger.Println("\n>>>session_id:", v_session_id, ", user_id :", v_user_id)

	if v_user_id == 0 {
		reloginPage(response, request)
		return
	}

	device_id := request.FormValue("device_id")
	v_oxy_min := request.FormValue("oxy_min")
	v_ph_min := request.FormValue("ph_min")
	v_ph_max := request.FormValue("ph_max")
	v_ammonia_nitrogen := request.FormValue("ammonia_nitrogen")
	v_temperature_min := request.FormValue("temperature_min")

	var oxy_min float64
	var ph_min float64
	var ph_max float64
	var ammonia_nitrogen float64
	var temperature_min float64

	var msg string = "Not an valid nubmer:"

	var err error

	if oxy_min, err = strconv.ParseFloat(v_oxy_min, 64); err != nil && v_oxy_min != "" {
		msg = msg + "  oxy_min          :" + v_oxy_min
	}
	if ph_min, err = strconv.ParseFloat(v_ph_min, 64); err != nil && v_ph_min != "" {
		msg = msg + "  ph_min           :" + v_ph_min
	}
	if ph_max, err = strconv.ParseFloat(v_ph_max, 64); err != nil && v_ph_max != "" {
		msg = msg + "  ph_max           :" + v_ph_max
	}
	if ammonia_nitrogen, err = strconv.ParseFloat(v_ammonia_nitrogen, 64); err != nil && v_ammonia_nitrogen != "" {
		msg = msg + "  ammonia_nitrogen :" + v_ammonia_nitrogen
	}
	if temperature_min, err = strconv.ParseFloat(v_temperature_min, 64); err != nil && v_temperature_min != "" {
		msg = msg + "  temperature_min  :" + v_temperature_min
	}

	if msg > "Not an valid nubmer:" {
		logger.Println("\nError:", err)
		logger.Println("\nMsg:", msg)
		fmt.Fprintf(response, `{"flag":-1,"message":"%s" }`, msg)
	} else {

		dbmsg := db_servicer.Set_Device_Margin(v_user_id, device_id, oxy_min, ph_min, ph_max, ammonia_nitrogen, temperature_min)

		//	logger.Println("dbmsg:", dbmsg)
		logger.Println("\n>>>Return to App Client:", dbmsg.Data)
		fmt.Fprint(response, dbmsg.Data)

		// Send_To_Device(device_id)

	}
}

func getDeviceMarginHandler(response http.ResponseWriter, request *http.Request) {
	// logger = log.New(os.Stdout, ">>>>>>>> Get Device Margin  :", log.LstdFlags|log.Lshortfile)
	v_session_id, v_user_id := getAccountName(request)

	device_id := request.FormValue("device_id")

	logger.Println("\n>>>session_id:", v_session_id, ", user_id :", v_user_id)
	if v_user_id == 0 {
		reloginPage(response, request)
		return
	}

	//	var responseStr []byte

	dbmsg := db_servicer.Get_Device_Margin(v_user_id, device_id)

	//	logger.Println("dbmsg:", dbmsg)
	logger.Println("\n>>>Return to App Client:", dbmsg.Data)
	fmt.Fprint(response, dbmsg.Data)

}

func fetchDeviceAlignHandler(response http.ResponseWriter, request *http.Request) {
	// logger = log.New(os.Stdout, ">>>>>>>> Command Device to Align :", log.LstdFlags|log.Lshortfile)

	v_session_id, v_user_id := getAccountName(request)

	device_id := request.FormValue("device_id")

	logger.Println("\n>>>session_id:", v_session_id, ", user_id :", v_user_id)

	if v_user_id == 0 {
		reloginPage(response, request)
		return
	}

	//	var responseStr []byte

	dbmsg := db_servicer.Fetch_Device_Align(v_user_id, device_id)

	//	logger.Println("dbmsg:", dbmsg)
	logger.Println("\n>>>Return to App Client:", dbmsg.Data)
	fmt.Fprint(response, dbmsg.Data)

	// Send_To_Device(device_id)
}

func cmdDeviceAlignHandler(response http.ResponseWriter, request *http.Request) {
	// logger = log.New(os.Stdout, ">>>>>>>> Command Device to Align :", log.LstdFlags|log.Lshortfile)

	v_session_id, v_user_id := getAccountName(request)

	device_id := request.FormValue("device_id")

	logger.Println("\n>>>session_id:", v_session_id, ", user_id :", v_user_id)

	if v_user_id == 0 {
		reloginPage(response, request)
		return
	}

	//	var responseStr []byte

	dbmsg := db_servicer.Cmd_Device_Align(v_user_id, device_id)

	// send2Device(device_id)
	chan2Device <- device_id

	//	logger.Println("dbmsg:", dbmsg)
	logger.Println("\n>>>Return to App Client:", dbmsg.Data)
	fmt.Fprint(response, dbmsg.Data)

	// Send_To_Device(device_id)
}

//func Send_To_Device( p_device_id string ) (flag int8, ip_addr  string , out_msg string) {

/*
func Send_To_Device( p_device_id string ) ( int8, string) {
// get list of down stream data from table dev_outgoing_log
	// send to devcie , use the current ip and port from device_list
	// update the status  of  dev_outgoing_log
	logger := log.New(os.Stdout, ">>>>>>>Send To Device :", log.LstdFlags|log.Lshortfile)


	v_flag, v_ip_addr, v_ret := db_servicer.Send_To_Device( p_device_id)

	if v_flag !=  0 {
		logger.Print("Error ")
		return -1, v_ip_addr // now v_ip_addr holds error msg

	}else {

		logger.Print("Dailing to :", v_ip_addr, "......")

		conn, _ := net.Dial("tcp", v_ip_addr)

		logger.Print("\nConnected to : ", conn.RemoteAddr())

		return  tcp_servicer.Proc_outgoing_msg(conn, v_ret)

	}
//		conn.SetReadDeadline(time.Now().Add(60 * 3.1 * time.Second)) // set 3 minutes timeout

}

*/
